import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormControl, Validators, AbstractControl } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';

// services
import { ConstantService } from '../../../../../core/services/constant.service';
import { ServerService } from '../../../../../core/services/server.service';
import { StorageService } from '../../../../../core/services/storage.service';
import { UtilService } from '../../../../../core/services/util.service';

// plugins
import * as moment from 'moment';
import _ from 'lodash';

@Component({
    selector: 'app-student-management',
    templateUrl: './student-management.component.html',
    styleUrls: ['./student-management.component.css']
})
export class StudentManagementComponent implements OnInit {
    studentForm: FormGroup;               // 班级表单
    isVisible: boolean = false;           // 是否显示modal
    isConfirmLoading: boolean = false;    // modal中点击保存的时候的过渡效果
    isViewStateUpdate: boolean = false;   // 页面是否是更新状态
    gradeList: object[] = [];             // 全部年级列表
    classList: object[] = [];             // 全部班级列表
    gradeIdAndClassIdList: object[] = []; // 年级和班级列表
    studentList: object[] = [];           // 全部学生列表
    schoolId: string;                     // 学校id
    currentUser: object;                  // 当前登录用户信息
    _current: number = 1;                 // 当前页
    _pageSize: number = 10;               // 每页数量
    _total: number = 1;                   // 数据总数
    _loading: boolean = true;             // 加载动画

    constructor(
        private fb: FormBuilder,
        private constant: ConstantService,
        private server: ServerService,
        private storage: StorageService,
        private message: NzMessageService,
        private util: UtilService
    ) {
        /**
         * 初始化学生表单
         * name: 姓名
         * studentId: 学号
         * schoolId: 学校id
         * gradeId: 年级id
         * classId: 班级id
         * parentName: 家长姓名
         * parentPhone: 家长手机号
         * idCard: 身份证号码
         * birthday: 出生日期
         * sex: 性别 1 男 2 女
         */
        this.studentForm = this.fb.group({
            _id: [null],
            name: [null, [Validators.required, Validators.maxLength(10)]],
            studentId: [null, [Validators.required, Validators.maxLength(20)]],
            gradeIdAndClassId: [[], Validators.required],
            parentName: [null, [Validators.required, Validators.maxLength(10)]],
            parentPhone: [null, Validators.required],
            idCard: [null, [Validators.required, Validators.minLength(18), Validators.maxLength(18)]],
            birthday: [null, Validators.required],
            sex: ['1', Validators.required]
        });
        this.schoolId = this.storage.getItem(this.constant.storage.currentUser)['schoolId']['_id'];
        this.currentUser = this.storage.getItem(this.constant.storage.currentUser);
    }

    ngOnInit() {
        this.getAllStudents();
    }

    /**
     * 显示modal,添加或更新班级信息
     * @param id 
     */
    async showModal(id) {
        this.isVisible = true;
        // 当前用户不是管理员
        // 首先获取年级列表和学科列表
        if (this.currentUser['isSchoolManager']) {
            await Promise.all([this.getAllGrades(), this.getAllClasses()]);
        } else {
            this.gradeList = this.currentUser['gradeIds'];
            this.classList = this.currentUser['classIds'];
        }
        // 转化年级和班级数据结构
        let options = [];
        for (let grade of this.gradeList) {
            const temp = {
                value: grade['_id'],
                label: grade['name'],
                children: []
            };
            for (let c of this.classList) {
                if (grade['_id'] === c['gradeId']['_id'] || grade['_id'] === c['gradeId']) {
                    temp['children'].push({
                        value: c['_id'],
                        label: c['name'],
                        isLeaf: true
                    });
                }
            }
            if (temp.children.length === 0) {
                temp['disabled'] = true;
            }
            options.push(temp);
        }
        this.gradeIdAndClassIdList = options;
        if (id) {
            this.isViewStateUpdate = true;
            const result = await this.server.fetch(this.constant.api.manage.student.findOne, { id });
            if (result) {
                const grade = _.filter(this.gradeList, (grade) => { return grade._id === result.data.gradeId; })[0];
                const c = _.filter(this.classList, (c) => { return c._id === result.data.classId; })[0];
                this.studentForm.setValue({
                    _id: result.data._id,
                    name: result.data.name,
                    studentId: result.data.studentId,
                    parentName: result.data.parentName,
                    parentPhone: result.data.parentPhone,
                    idCard: result.data.idCard,
                    birthday: moment(result.data.birthday),
                    sex: String(result.data.sex),
                    gradeIdAndClassId: [{ value: grade._id, label: grade.name }, { value: c._id, label: c.name }]
                });
            }
        } else {
            this.isViewStateUpdate = false;
        }
    }

    /**
     * 获取年级列表
     * @param schoolId 
     */
    async getAllGrades() {
        const param = {
            schoolId: this.schoolId
        };
        const allGrades = await this.server.fetch(this.constant.api.manage.grade.findAll, param);
        if (allGrades) {
            this.gradeList = allGrades.data.data;
        }
    }

    /**
     * 获取班级列表
     * @param schoolId 
     */
    async getAllClasses() {
        const param = {
            schoolId: this.schoolId
        };
        const allClasses = await this.server.fetch(this.constant.api.manage.classM.findAll, param);
        if (allClasses) {
            this.classList = allClasses.data.data;
        }
    }

    /**
     * 关闭modal
     * @param e 
     */
    handleCancel(e): void {
        this.studentForm.setValue({
            _id: null,
            name: null,
            studentId: null,
            parentName: null,
            parentPhone: null,
            idCard: null,
            birthday: null,
            sex: '1',
            gradeIdAndClassId: []
        });
        this.isVisible = false;
    }

    // 获取表单项
    getFormControl(name): AbstractControl {
        return this.studentForm.controls[name];
    }

    /**
     * 保存 || 更新
     * @param e 
     * @param school 
     */
    async handleOk(e, student): Promise<void> {
        student.schoolId = this.schoolId;
        student.gradeId = student.gradeIdAndClassId[0];
        student.classId = student.gradeIdAndClassId[1];
        delete student.gradeIdAndClassId;
        this.isConfirmLoading = true;
        // 转换时间格式
        student.birthday = moment(student.birthday).format('YYYY-MM-DD');
        // 验证家长手机号码或者固话号码
        const phone_regexp = /^[1][3,4,5,7,8][0-9]{9}$/;
        const telephone_regexp = /^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;
        if (!phone_regexp.test(student.parentPhone) && !telephone_regexp.test(student.parentPhone)) {
            this.message.error('抱歉,家长联系方式有误,请重新输入');
            this.isConfirmLoading = false;
            return;
        }
        // 保存
        const result = await this.server.fetch(this.constant.api.manage.student[this.isViewStateUpdate ? 'update' : 'save'], student);
        if (result) {
            this.message.success('保存学生成功');
            if (!this.isViewStateUpdate) {
                // 清空表单
                this.studentForm.controls['name'].reset();
                this.studentForm.controls['studentId'].reset();
                this.studentForm.controls['idCard'].reset();
                this.studentForm.controls['parentName'].reset();
                this.studentForm.controls['parentPhone'].reset();
                this.studentForm.controls['birthday'].reset();
                this.studentForm.controls['sex'].setValue(1);
            }
            this.isConfirmLoading = false;
            this.getAllStudents();
            this.isVisible = false;
        } else {
            this.isConfirmLoading = false;
        }
    }

    /**
     * 获取全部班级列表
     */
    async getAllStudents(): Promise<void> {
        const param = {
            schoolId: this.schoolId,
            limit: this._pageSize
        };
        if (!this.currentUser['isSchoolManager']) {
            param['gradeIds'] = this.currentUser['gradeIds'].map((g) => { return g._id; });
            param['classIds'] = this.currentUser['classIds'].map((c) => { return c._id; });
        }
        if (this._current !== 1) {
            param['date'] = this.studentList[this.studentList.length - 1]['createDate'];
        }
        const allStudents = await this.server.fetch(this.constant.api.manage.student.findAll, param);
        if (allStudents) {
            this.studentList = allStudents.data.data;
            this._total = allStudents.data.count;
            this._loading = false;
        } else {
            this._loading = false;
        }
    }

    /**
     * 出生日期选择控制
     * 不能选择今天之后的日期
     */
    _disabledDate = function (current) {
        return current && current.getTime() > Date.now();
    };

    async del(id): Promise<void> {
        const result = await this.server.fetch(this.constant.api.manage.student.del, { id });
        if (result) {
            this.message.success('删除成功');
            this.getAllStudents();
        }
    }

}
